import AsyncStorage from '@react-native-async-storage/async-storage';

class UseStorage {
  /**
   * @desc set data
   * @param {string} key
   * @param {any} value
   *
   * @returns {Promise}
   */
  static set(key, value) {
    return AsyncStorage.setItem(key, JSON.stringify(value));
  }
  /**
   * @desc GET data
   * @param {string} key
   *
   *
   * @returns {Promise}
   */
  static async get(key) {
    try {
      const value = await AsyncStorage.getItem(key);
      console.log(value);
      if (value && value !== null) {
        console.log(JSON.parse(value));
        return JSON.parse(value);
      }
    } catch (error) {
      return null;
    }
  }
  /**
   * @desc UPDATE data
   * @param {string} key
   * @param {any} newValue
   *
   * @returns {Promise}
   */
  static update(key, newValue) {
    return AsyncStorage.getItem(key).then(oldVal => {
      newValue =
        typeof newValue === 'string'
          ? newValue
          : Object.assign({}, JSON.parse(oldVal), newValue);
      return AsyncStorage.setItem(key, JSON.stringify(newValue));
    });
  }
  /**
   * @desc delete data
   * @param {string} key
   */
  static delete(key) {
    return AsyncStorage.removeItem(key);
  }
  /**
   * @desc 清空
   *
   */
  static clear() {
    return AsyncStorage.clear();
  }
}
export default UseStorage;
